package uit.nfcmenu.manager;

import java.util.ArrayList;
import java.util.Hashtable;

import uit.nfcmenu.db.adapter.ItemAdapter;
import uit.nfcmenu.db.model.ItemModel;
import uit.nfcmenu.util.CommConstant;
import uit.nfcmenu.util.ConvertImg;
import uit.nfcmenu.webservice.MyException;
import uit.nfcmenu.webservice.WSMapping;
import android.content.Context;
import android.graphics.Bitmap;


public class ItemManager {

	private static ItemManager instance;
	private Context mContext;
	protected ItemAdapter mItemAdapter;

	public ItemManager(Context context) {
		mContext = context;
		mItemAdapter = new ItemAdapter(mContext);
		mItemAdapter = new ItemAdapter(mContext);
	}

	public static ItemManager getInstance(Context context) {
		if (instance == null) {
			instance = new ItemManager(context);
		}
		return instance;
	}

	public ArrayList<ItemModel> getAllItemsInDB() {
		return mItemAdapter.selectAll();
	}

	public void deleteAllItems() {
		mItemAdapter.deleteDatabase();
	}

	public void clearItems() {
		mItemAdapter.deleteDatabase();
	}

	public ArrayList<ItemModel> getItemsByMenu(int mainId) {
		ArrayList<ItemModel> models = new ArrayList<ItemModel>();
		models.addAll(mItemAdapter.getItemsByMenu(mainId));
		return models;
	}

	public ArrayList<ItemModel> getAllItems() {
		ArrayList<ItemModel> models = getAllItemsInDB();

		// create temp memory for items in app
		CommConstant.item = new Hashtable<Integer, String>();
		int  count = models.size();
		for (int i = 0; i < count; i++) {
			CommConstant.item.put(models.get(i).getId(), 
					models.get(i).getName());
		}
		return models;
	}

	public void updateItems() throws MyException {
		// get data from server
		ArrayList<ItemModel> models;
		models = WSMapping.getAllItemsFromServer(mContext);

		// update data to db
		ItemAdapter adapter = new ItemAdapter(mContext);
		if (models != null && models.size() > 0) {
			// TODO build #1 => build #2
			// solution build #1
//			ItemModel model;
//			for (int i = 0; i < models.size(); i++) {
//				model = adapter.loadItemModel(models.get(i).getId());
//				if (model == null) {
//					adapter.insertItemModel(models.get(i));
//				} else {
//					adapter.updateItemModel(models.get(i));
//				}
//			}
			// solution build #2
			// drop db and update all new date into db
			adapter.deleteDatabase();
			adapter.insertItemModels(models);
		}
	}

	public Bitmap getBitmapById(int itemId) {
		Bitmap bitmap = null;
		ItemAdapter adapter = new ItemAdapter(mContext);
		String bitmapStr = adapter.loadStringBitmapById(itemId);
		bitmap = ConvertImg.decodeBase64(bitmapStr);
		return bitmap;
	}
}
